package com.kk.springboot_001.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kk.springboot_001.mapper.FruitMapper;
import com.kk.springboot_001.pojo.dto.Fruit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FruitServiceImpl implements FruitService{

    @Autowired
    private FruitMapper fruitMapper;

    @Override
    public Fruit addFruit(Fruit fruit) {
        // 检查水果是否已存在
        QueryWrapper<Fruit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", fruit.getUserId()) // 检查同一个用户
                .eq("fruit_name", fruit.getFruitName());
        Fruit existingFruit = fruitMapper.selectOne(queryWrapper);
        if (existingFruit != null) {
            // 如果水果已存在，抛出自定义异常
            throw new RuntimeException("该水果已存在于您的列表中。");
        }
        fruitMapper.insert(fruit);
        return fruit;
    }

    /**
     * 获取用户水果列表（分页）
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<Fruit> getFruitsByUserIdWithPagination(Integer userId, int page, int size) {
        // 创建分页对象，指定当前页和每页大小
        Page<Fruit> fruitPage = new Page<>(page, size);

        // 创建查询条件
        QueryWrapper<Fruit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 执行分页查询
        return fruitMapper.selectPage(fruitPage, queryWrapper);
    }
}
